//package com.ksd.web.controller.service;
//
//import com.ksd.api.tool.VodStatus;
//import com.ksd.common.config.PlayControlConfig;
//import com.ksd.common.core.domain.AjaxResult;
//import com.ksd.common.enums.UserStatus;
//import com.ksd.common.utils.StringUtils;
//import com.ksd.common.utils.file.FileUploadUtils;
//import com.ksd.quartz.util.TaskConstans;
//import com.ksd.system.domain.*;
//import com.ksd.system.service.*;
//import com.ksd.web.controller.tool.ChinesePinyinConverter;
//import com.ksd.web.controller.upload.*;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//import javax.xml.bind.JAXBContext;
//import javax.xml.bind.JAXBException;
//import javax.xml.bind.Unmarshaller;
//import java.io.File;
//import java.util.ArrayList;
//import java.util.List;
//
//@Service
//public class SongFileService {
//
//    public final Logger logger = LoggerFactory.getLogger(SongFileService.class);
//    @Autowired
//    private ISysOperLogService sysOperLogService;
//    @Autowired
//    private ISysSongDataService sysSongDataService;
//    @Autowired
//    private ISysTvDataService sysTvDataService;
//    @Autowired
//    private ISysTvTypeService sysTvTypeService;
//    @Autowired
//    private ISysSongDetailService sysSongDetailService;
//    @Autowired
//    private ISysBatchService sysBatchService;
//
//    public static final String[] IMAGE_EXTENSION = { "bmp", "gif", "jpg", "jpeg", "png" ,"webp"};
//
//    //MP3、AAC、WMA、AD-3、RA、DTS、FLAC、APE
//    public static final String[] SONG_EXTENSION = { "mp3", "aac","wma","ad-3","ra","dts","flac","ape","ogg" };
//    public static final String[] WORD_EXTENSION = { "txt", "xml","lrc" };
//
//    public AjaxResult setSongUpdateFile(String uploadFilePath, String userName,String taskId) {
//        System.out.println("开始进行歌曲的config.xml文件的解析");
//        System.out.println("选中已上传的文件路径,需要是导入歌曲文件的三层文件夹:"+uploadFilePath);
//        File file = new File(uploadFilePath);
//
//        /**
//         * 解压缩文件格式:视频格式:.mp3/
//         * 图片:.png/.jpg
//         * 歌词:.txt
//         */
//        //由于歌曲和电影的config.xml文件格式不同,一个xml文件可能包含多个歌曲,所以需要先解析xml文件,再区分文件
//        //以专辑的形式区分
//        List<File> xmlFiles = new ArrayList<>();
//        List<File> songFiles = new ArrayList<>();//可能存在多首歌
//        List<File> imageFiles = new ArrayList<>(); //一个专辑图片
//        List<File> recommendBannerFiles = new ArrayList<>(); //一个推荐图片
//        List<File> wordFiles = new ArrayList<>();//可能存在多首歌的歌词
//        String filePathStart = PlayControlConfig.getNginxRootPath()+File.separator+file.getName();
//        System.out.println("实际文件存储地址:"+filePathStart);
//        //进行文件区分
//        if (file.isDirectory()) {
//            File[] files = file.listFiles();
//            System.out.println("files size:"+files.length);
//            for (File everyFile : files) {
//                String name = everyFile.getName();
//                int i = name.lastIndexOf(".");
//                String substring = name.substring(i+1, name.length());
//                if (FileUploadUtils.isAllowedExtension(name, TaskConstans.SONG_XML_NAME)){
//                    xmlFiles.add(everyFile);
//                }
//                if(FileUploadUtils.isAllowedExtension(substring,SONG_EXTENSION)){
//                    songFiles.add(everyFile);
//                }
//                if(FileUploadUtils.isAllowedExtension(substring,IMAGE_EXTENSION)){
//                    imageFiles.add(everyFile);
//                }
//                if(FileUploadUtils.isAllowedExtension(substring,IMAGE_EXTENSION)){
//                    if (name.startsWith("logo")){
//                        imageFiles.add(everyFile);
//                    }
//                    if (name.startsWith("recommend")){
//                        recommendBannerFiles.add(everyFile);
//                    }
//                }
//                if (FileUploadUtils.isAllowedExtension(substring,WORD_EXTENSION)){
//                    wordFiles.add(everyFile);
//                }
//            }
//        }
//        if (StringUtils.isNotNull(xmlFiles) && StringUtils.isNotNull(songFiles) && StringUtils.isNotNull(imageFiles) && StringUtils.isNotNull(wordFiles)) {
//            System.out.println("文件格式正确");
//        }else{
//            System.out.println("文件格式不正确");
//            //删除批量操作
//            // sysBatchService.deleteSysBatchByTaskId(taskId);
//            sysOperLogService.insertOperlogApiError("压缩包内的文件格式不正确,请校验文件:"+uploadFilePath);
//            return AjaxResult.error("压缩包内的文件格式不正确,请校验文件");
//        }
//
//        SysSongDetail sysSongDetail = new SysSongDetail();
//
//        File xmlFile = xmlFiles.get(0);
//        String absolutePath = xmlFile.getAbsolutePath();
//        String imgFileEnd = "";
//        String recommendFileEnd = "";
//        try {
//            JAXBContext jaxbContext = JAXBContext.newInstance(SongResources.class);
//            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
//            SongResources resources = (SongResources) unmarshaller.unmarshal(new File(absolutePath));
//            SongContent content = resources.getContent();
//            Recommend recommend = content.getRecommend();
//            String subcategory = content.getSubcategory();
//            imgFileEnd = content.getImageFile();
//            if (subcategory.indexOf("/") != -1) {
//                String[] split = subcategory.split("/");
//                String type = split[0];
//                String typeDataDetail = split[1];
//
//                SysTvData sysTvData = new SysTvData();
//                sysTvData.setTypeId(Long.valueOf(SysTvType.songDefaultId));
//                sysTvData.setName(type);
//                List<SysTvData> sysTvDatas = sysTvDataService.selectSysTvDataList(sysTvData);
//                System.out.println("查询音乐分类个数:"+sysTvDatas.size()+"================="+sysTvData.getName()+"============"+sysTvData.getTypeId());
//                Long tvDataId;
//                if (sysTvDatas.size() > 0) {
//                    tvDataId = sysTvDatas.get(0).getId();
//                }else{
//                    sysTvData.setStatus(UserStatus.OK.getCode());
//                    System.out.println("=========================新增音乐类型:"+sysTvData.getName());
//                    sysTvDataService.insertSysTvData(sysTvData);
//                    tvDataId = sysTvData.getId();
//                }
//                System.out.println("查询最新音乐类型:"+tvDataId);
//                //专辑分类
//                sysSongDetail.setFileType(Integer.valueOf(SysTvType.songDefaultId));
//                sysSongDetail.setTypeData(tvDataId);
//                sysSongDetail.setTitle(content.getTitle());
//                sysSongDetail.setDetail(typeDataDetail);
//                sysSongDetail.setDirector(content.getDirector());
//                sysSongDetail.setNum(songFiles.size());
//                if (StringUtils.isNotNull(recommend)){
//                    sysSongDetail.setIsRecommend(StringUtils.trim(recommend.getIsRecommend()));
////                    if (sysSongDetail.getIsRecommend().equals("1")){
////                        sysSongDetail.setRecommendBanner(filePathStart+StringUtils.trim(recommend.getRecommendBanner()));
////                        recommendFileEnd = StringUtils.trim(recommend.getRecommendBanner());
////                    }
//                    if (StringUtils.isNotEmpty(recommend.getRecommendBanner())){
//                        sysSongDetail.setRecommendBanner(filePathStart+StringUtils.trim(recommend.getRecommendBanner()));
//                        recommendFileEnd = StringUtils.trim(recommend.getRecommendBanner());
//                    }
//                }
//                String keyWord = ChinesePinyinConverter.convertToPinyin(sysSongDetail.getTitle()).replaceAll("\\s+", "");
//                sysSongDetail.setKeyWord(keyWord);
//                SysSongDetail sysSongDetailTemp  = new SysSongDetail();
//                sysSongDetailTemp.setKeyWord(sysSongDetail.getKeyWord());
//                sysSongDetailTemp.setTitle(sysSongDetail.getTitle());
//                sysSongDetailTemp.setTypeData(sysSongDetail.getTypeData());
//                List<SysSongDetail> sysSongDetails = sysSongDetailService.selectSysSongDetailList(sysSongDetailTemp);
//                System.out.println("查询是否已存在该专辑:"+sysSongDetails.size()+"=========="+sysSongDetailTemp.getTitle()+"======"+sysSongDetailTemp.getKeyWord()+"========"+sysSongDetailTemp.getTypeData());
//                if (sysSongDetails.size() > 0) {
//                    sysSongDetail.setId(sysSongDetails.get(0).getId());
//                    System.out.println("更新专辑数据:"+sysSongDetail.getId());
//                    sysSongDetailService.updateSysSongDetail(sysSongDetail);
//                }else{
//                    System.out.println("新增专辑数据:"+sysSongDetail.getTitle());
//                    sysSongDetail.setStatus(UserStatus.OK.getCode());
//                    sysSongDetailService.insertSysSongDetail(sysSongDetail);
//                }
//
//            }
//
//            List<SongEpisode> episode = content.getEpisode(); //可能存在多首歌曲
//            for (SongEpisode episodeTemp : episode) {
//                SysSongData sysSongData = new SysSongData();
//                sysSongData.setImageFile(filePathStart+content.getImageFile()); //专辑图片
//                sysSongData.setStatus(VodStatus.OK.getCode());
//                sysSongData.setUserName(userName);
//                sysSongData.setContentTitle(sysSongDetail.getTitle());
//                sysSongData.setFileType(Integer.valueOf(SysTvType.songDefaultId));
//                sysSongData.setTypeData(Integer.valueOf(sysSongDetail.getTypeData().toString()));
//                sysSongData.setIsRecommend(sysSongDetail.getIsRecommend());
//                sysSongData.setRecommendBanner(sysSongDetail.getRecommendBanner());
//
//                String songWord = episodeTemp.getLyricFile();
//                String videoFile = episodeTemp.getVideoFile();
//                String singer = episodeTemp.getSinger();
//                String title = episodeTemp.getTitle();
//                if (StringUtils.isNotEmpty(songWord)) {
//                    sysSongData.setSongWord(filePathStart+songWord);
//                }
//                if (StringUtils.isNotEmpty(videoFile)) {
//                    sysSongData.setVideoFile(filePathStart+videoFile);
//                }
//                if (StringUtils.isNotEmpty(singer)) {
//                    sysSongData.setSinger(singer);
//                }
//                if (StringUtils.isNotEmpty(title)) {
//                    sysSongData.setTitle(title);
//                }
//                String keyWord = ChinesePinyinConverter.convertToPinyin(sysSongData.getTitle()).replaceAll("\\s+", "");
//                sysSongData.setKeyWord(keyWord);
//                sysSongData.setDirector(sysSongDetail.getDirector());
//                sysSongData.setDescription(sysSongDetail.getDetail());
//                sysSongData.setTaskId(taskId);
//
////                String videoFileSql = PlayControlConfig.getMappedAddress()+File.separator+file.getName()+videoFile;
////                System.out.println("校验数据库文件存储地址:"+videoFileSql);
//                //插入之前需要查询一下该文件内容是否已上传,根据视频地址
//                SysSongData sysSongDataTemp = new SysSongData();
////                sysSongDataTemp.setVideoFile(videoFileSql);
//                sysSongDataTemp.setTitle(sysSongData.getTitle());
//                sysSongDataTemp.setFileType(Integer.valueOf(SysTvType.songDefaultId));
//                sysSongDataTemp.setTypeData(Integer.valueOf(sysSongData.getTypeData().toString()));
//                sysSongDataTemp.setDetailId(sysSongDetail.getId());
//                List<SysSongData> sysSongData1 = sysSongDataService.selectSysSongDataList(sysSongDataTemp);
////                System.out.println("查询数据上传文件是否已入库:"+sysSongData1.size()+"======"+"=================歌曲类型:"+sysSongData.getTypeData());
//                if (sysSongData1.size() > 0) {
//                    System.out.println("更新数据");
//                    //先将其删除
////                    File fileExit = new File(videoFileSql);
////                    System.out.println("查询改文件是否已导入:"+sysSongData1.get(0).getVideoFile()+"==========="+sysSongData1.get(0).getId()+"==========="+sysSongData1.get(0).getTitle());
//                    sysSongData.setId(sysSongData1.get(0).getId());
//                    sysSongDataService.updateSysSongData(sysSongData);
//                    sysSongData = sysSongDataService.selectSysSongDataById(sysSongData1.get(0).getId());
//                }else{
//                    System.out.println("插入数据库库中");
//                    sysSongDataService.insertSysSongData(sysSongData);
//                    System.out.println("新增歌曲:"+sysSongData.getId());
//                }
//                sysSongData = sysSongDataService.selectSysSongDataById(sysSongData.getId());
//                String songWordTemp = sysSongData.getSongWord();
//                String videoFileTemp = sysSongData.getVideoFile();
//
//                //精确查找对应的歌词和歌曲文件
//                System.out.println("songFile size:"+songFiles.size());
//                for (File songFile : songFiles) {
//                    String name = songFile.getName();
////                    System.out.println(sysSongData.getTitle()+"##########歌曲文件名称:%%%%%%%%%%"+name+"==========="+songFile.getAbsolutePath());
//                    int i = name.lastIndexOf(".");
//                    String substring = name.substring(i+1, name.length());
//                    if (FileUploadUtils.isAllowedExtension(substring,SONG_EXTENSION)){
//                        String[] split = name.split("\\.");
////                        if (split[0].equals(sysSongData.getTitle())){   //要求title的值和文件歌曲名对应
//                        if (split[0].indexOf(sysSongData.getTitle()) != -1 && split[0].indexOf(sysSongData.getSinger()) != -1){
////                            System.out.println("切割后歌曲==========:"+split.length+"================="+split[0]+"===="+sysSongData.getSinger()+"====="+sysSongData.getTitle());
//                            String songFilePath = songFile.getAbsolutePath();
//                            FileUsingIO.moveFile(songFilePath,videoFileTemp); //歌曲
//                            System.out.println("移动歌曲:"+songFilePath);
//                            System.out.println("");
//                            System.out.println(videoFileTemp);
//                        }
//                    }
//                }
//                System.out.println("wordFiles size:"+wordFiles.size());
//                for (File wordFile : wordFiles) {
//                    String name = wordFile.getName();
////                    System.out.println(sysSongData.getTitle()+"============歌词文件名称:@@@@@@@@"+name+"==========="+wordFile.getAbsolutePath());
//                    int i = name.lastIndexOf(".");
//                    String substring = name.substring(i+1, name.length());
//                    if (FileUploadUtils.isAllowedExtension(substring,WORD_EXTENSION)){
//                        String[] split = name.split("\\.");
////                        if (split[0].equals(sysSongData.getTitle())){ //要求title的值与歌词文件名对应
//                        if (split[0].indexOf(sysSongData.getTitle()) != -1 && split[0].indexOf(sysSongData.getSinger()) != -1){
////                            System.out.println("切割后歌词:================="+split[0]+"========="+sysSongData.getSinger()+"==============="+sysSongData.getTitle());
//                            String wordFilePath = wordFile.getAbsolutePath();
//                            FileUsingIO.moveFile(wordFilePath,songWordTemp); //歌词
//                            System.out.println("移动歌词:"+wordFilePath);
//                            System.out.println("");
//                            System.out.println(songWordTemp);
//                        }
//                    }
//                }
//            }
//        } catch (JAXBException e) {
//            e.printStackTrace();
//        }
//
//
//        //最后移动专辑封面
//        String imageFilePath = imageFiles.get(0).getAbsolutePath();
//        String imageFileTemp = filePathStart + File.separator + imgFileEnd;
//        System.out.println("img移动:"+imageFilePath);
//        System.out.println("imgFileEnd:"+imgFileEnd);
//        System.out.println("img移动:"+imageFileTemp);
//        FileUsingIO.moveFile(imageFilePath,imageFileTemp);
//
//        //最后移动config文件
//        String xmlFilePath = xmlFiles.get(0).getAbsolutePath();
//        String name = xmlFile.getName();
//        System.out.println("复制的xml文件名:"+name);
//        File fileTemp = new File(imageFileTemp);
//        File parentFile = fileTemp.getParentFile();
//        String newXmlPath = parentFile + File.separator + name;
//        System.out.println("移动复制xml文件源文件地址:   "+xmlFilePath);
//        System.out.println("移动复制xml文件目的文件地址: "+newXmlPath);
//        FileUsingIO.moveFile(xmlFilePath,newXmlPath);
//        //最后移动推荐图
//        if (StringUtils.isNotEmpty(recommendBannerFiles)){
//            File recommendFile = recommendBannerFiles.get(0);
//            String recommendFilePath =recommendFile.getAbsolutePath();
//            String recommendFileTemp = filePathStart + File.separator + recommendFileEnd;
//            System.out.println("recommend文件复制:"+recommendFilePath);
//            System.out.println("recommendFileEnd:"+recommendFileEnd);
//            System.out.println("recommend文件复制:"+recommendFileTemp);
//            FileUsingIO.moveFile(recommendFilePath,recommendFileTemp);
//        }
//        //进行文件映射地址的更新
//        try {
//            JAXBContext jaxbContext = JAXBContext.newInstance(SongResources.class);
//            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
//            SongResources resources = (SongResources) unmarshaller.unmarshal(new File(absolutePath));
//            SongContent content = resources.getContent();
//
//            List<SongEpisode> episode = content.getEpisode();
//            String mapperTemp = PlayControlConfig.getMappingPath()+File.separator+file.getName();
//            sysSongDetail.setImageFile(mapperTemp+content.getImageFile());
//            sysSongDetailService.updateSysSongDetail(sysSongDetail);
//            for (SongEpisode songEpisode : episode) {
//                //            SysContentData sysContentDataTemp = sysContentDataService.selectSysContentDataById(sysContentData.getId());
//                SysSongData songDataUpdate = new SysSongData();
//                songDataUpdate.setTitle(songEpisode.getTitle());
//                songDataUpdate.setSinger(songEpisode.getSinger());
//                SysSongData sysSongDataTemp = sysSongDataService.selectSysSongDataList(songDataUpdate).get(0);
//
//                sysSongDataTemp.setImageFile(mapperTemp+content.getImageFile());
//                sysSongDataTemp.setVideoFile(mapperTemp+songEpisode.getVideoFile());
//                sysSongDataTemp.setSongWord(mapperTemp+songEpisode.getLyricFile());
//                sysSongDataTemp.setDetailId(sysSongDetail.getId());
//                sysSongDataService.updateSysSongData(sysSongDataTemp);
//            }
//
//        } catch (JAXBException e) {
//            e.printStackTrace();
//        }
//
//        return AjaxResult.success();
//    }
//
//    public static void main(String[] args) {
//        String name = "冷雨夜.mp3";
//        String[] split = name.split("\\.");
//        int i = name.lastIndexOf(".");
//        String substring = name.substring(i+1, name.length());
//        boolean allowedExtension = FileUploadUtils.isAllowedExtension(substring, SONG_EXTENSION);
//        System.out.println(allowedExtension);
//        System.out.println(split.length);
//        System.out.println(split[0]);
//    }
//}
